//
//  CSSettleDeliveryUpdatePlateTVC.m
//  ProjectforHDX
//
//  Created by yinda on 16/8/8.
//  Copyright © 2016年 H.DX. All rights reserved.
//

#import "CSSettleDeliveryUpdatePlateTVC.h"
#import "settleDeliveryHeaderCell.h"
#import "settleDeliveryCell.h"
#import "CSSettleDeliveryUpPlateVC.h"
#import "SettleDeliveOrder.h"
#import "BottomOperationView.h"
#import "SettleDeliverPlate.h"
#import "DeliveryDetailsVC.h"

@interface CSSettleDeliveryUpdatePlateTVC ()<UITableViewDataSource,UITableViewDelegate,CSSettleDeliveryUpPlateVCDelegate>
{
    BOOL isMJRefresh;
}
//m模型数组
@property(nonatomic ,strong)NSMutableArray *plateArray;
//字典数组
@property (nonatomic, strong) NSMutableArray *plateDicArr;

@property(nonatomic,strong)UITableView *tableView;

@property(nonatomic ,strong)UIView *bottomView;

@property (nonatomic, strong) SettleDeliveOrder *model;

@property (nonatomic,assign)CGFloat cellHeight;

@property(nonatomic ,strong)NSString *modifyPermissions;

@property (nonatomic, strong) NSArray *operationPermissions;

@end

@implementation CSSettleDeliveryUpdatePlateTVC


-(NSMutableArray *)plateDicArr
{
    if (!_plateDicArr) {
        _plateDicArr = [[NSMutableArray alloc]init];
    }
    return _plateDicArr;
}


-(NSMutableArray *)plateArray
{
    if (!_plateArray) {
        _plateArray = [[NSMutableArray alloc]init];
    }
    return _plateArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self requestDetails];
    [self setupView];
    
}


#pragma mark 添加下拉刷新
- (void)addHeader
{
    if(self.tableView.header==nil){
        __weak __typeof(self) weakSelf = self;
        // 添加上拉刷新头部控件
        self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            if(isMJRefresh){
                isMJRefresh=NO;
                // 进入刷新状态后会自动调用这个block
                [weakSelf requestDetails];
            }
        }];
        // 马上进入刷新状态
        [self.tableView.header beginRefreshing];
    }
    else
    {
        // 马上进入刷新状态
        [self.tableView.header beginRefreshing];
    }
}

#pragma -mark 系统自动推荐客服发货和仓管发货清单共用接口
- (void)requestDetails {
    [[BDHUD sharedManager] showBDHUD:self.view title:@"HUD.title"];
    sleep(0.5);
    [[BDHUD sharedManager] dismissHUD];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"orderCode"] = self.orderCode;
    
    [AFHttpTool postJsonDatawithUrl:@"recommendShipping" parameters:[params mutableCopy] success:^(id responseObject) {

        if(1==[[[responseObject objectForKey:@"head"] objectForKey:@"status"] intValue]){
            if([[responseObject objectForKey:@"data"] isKindOfClass:[NSDictionary class]]){
              //处理数据
                [self loadData:[responseObject objectForKey:@"data"]];
                isMJRefresh=YES;
                [self.tableView.header endRefreshing];
            }
            else
            {
                [self.tableView.header endRefreshing];
            }
        }
        else{
            //返回数据出问题 弹出服务器返回信息
            if([[[responseObject objectForKey:@"head"] allKeys] containsObject:@"info"]&&![UtilCheck DataIsNuLL:[[responseObject objectForKey:@"head"] objectForKey:@"info"]]){
                [[BDHUD sharedManager] showWords:[[responseObject objectForKey:@"head"] objectForKey:@"info"]];
            }
            else {
                [[BDHUD sharedManager] showWords:[THMangerTool language:@"HUD.nothing"]];
            }
            
        }
    } fail:^(id responseObject, NSError *error) {
        isMJRefresh=YES;
        [self.tableView.header endRefreshing];
        [[BDHUD sharedManager] dismissHUD];
        if ([[error.userInfo objectForKey:@"NSLocalizedDescription"] isEqualToString:@"请求超时。"]) {
            [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.time.out"]];
        }else {
            [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.network.interruption"]];
        }
    }];
    
}


#pragma -mark 处理获取的数据
-(void)loadData:(NSDictionary *)data
{
    
    NSDictionary *order = [data objectForKey:@"orderInfo"];

    SettleDeliveOrder *model = [[SettleDeliveOrder alloc]init];
    [model setValuesForKeysWithDictionary:order];
    NSMutableArray *platesDicArr = [data objectForKey:@"recommended"];
    NSMutableArray *plateArr = [NSMutableArray array];
    for (int i =0 ; i<platesDicArr.count; i++) {
        SettleDeliverPlate *plate = [[SettleDeliverPlate alloc]init];
        [plate setAttributes:platesDicArr[i]];
        plate.badSN = [platesDicArr[i] objectForKey:@"badSN"];
        
        [plateArr addObject:plate];
    }
    self.plateArray = plateArr;
    self.plateDicArr = platesDicArr;
    
    self.model = model;
    //底部view
    NSDictionary *permissions = [data objectForKey:@"permissions"];
    NSLog(@"%@",permissions);
    BottomOperationView *bottom = [[BottomOperationView alloc]initWithOperationArray:permissions[@"operationPermissions"] AndOperationType:@"" btnClick:^(long tag) {
        NSInteger totolQty  = 0;
        NSLog(@"打%@",_plateDicArr);
        for (int i = 0; i < self.plateDicArr.count; i++) {
            totolQty +=  [self.plateDicArr[i][@"partsCount"] integerValue];
        }
        
        if (totolQty  < [self.model.count integerValue]) {
            [[BDHUD sharedManager] showWords:[THMangerTool language:@"setting.stockInsufficient"]];
        }
        else{
        [self settleDelivery:tag];
        }
    }];
    [bottom setFrame:CGRectMake(0, SCREEN_HEIGHT-60 - 60, SCREEN_WIDTH, 60)];
    [self.view addSubview:bottom];
    
    
    
    [self.tableView reloadData];
}

#define CELL_LINE_COLOR [UtilCheck hexStringToColor:@"e1e1df" alpha:1]
#pragma -mark 初始化界面
-(void)setupView
{
    isMJRefresh = YES;
    self.navColor = SYSTEM_COLOR;
    self.labnav.textColor = [UIColor whiteColor];
    self.labnav.text = [THMangerTool language:@"CSSettleDeliveryUpdatePlateTVC.title"];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-40-80) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableHeaderView =  [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, -1)];
    self.tableView.viewController.automaticallyAdjustsScrollViewInsets = NO;
    self.tableView.backgroundColor = [UIColor colorWithRed:241/255.0 green:246/255.0 blue:250/255.0 alpha:1.0];
    [self addHeader];
   

}

typedef enum
{
    CSSettleDeliveryTypeArrage=1,
    CSSettleDeliveryTypeQuick=2,
} CSSettleDeliveryType;


//底部按钮点击事件
-(void)settleDelivery:(long)tag
{
    
    switch (tag) {
        case CSSettleDeliveryTypeArrage:
        {
            [self arrayDeliver];
        }
            break;
        case CSSettleDeliveryTypeQuick:
        {
            [self queciDeliver];
        }
            break;
            
        case 3://发货
        {
            DeliveryDetailsVC *vc = [[DeliveryDetailsVC alloc]init];
            vc.orderCode = self.orderCode;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;

            
        default:
            break;
    }
}

#pragma -mark 快速发货
-(void)queciDeliver
{
    [[BDHUD sharedManager] showBDHUD:self.view title:@"HUD.title"];
    sleep(0.5);
    [[BDHUD sharedManager] dismissHUD];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"orderCode"] = self.orderCode;
    if (self.logisticsInfo) {
        params[@"logisticsInfo"] = self.logisticsInfo;
    }
    [AFHttpTool postJsonDatawithUrl:@"/fastDelivery" parameters:[params mutableCopy] success:^(id responseObject) {
        if(1==[[[responseObject objectForKey:@"head"] objectForKey:@"status"] intValue]){
            if([[responseObject objectForKey:@"data"] isKindOfClass:[NSDictionary class]]){
                [[BDHUD sharedManager] showWords:[[responseObject objectForKey:@"head"] objectForKey:@"info"]];
                [self.navigationController popViewControllerAnimated:YES];
            }
            else
            {
                [self.tableView.header endRefreshing];
            }
        }
        else{
            //返回数据出问题 弹出服务器返回信息
            if([[[responseObject objectForKey:@"head"] allKeys] containsObject:@"info"]&&![UtilCheck DataIsNuLL:[[responseObject objectForKey:@"head"] objectForKey:@"info"]]){
                [[BDHUD sharedManager] showWords:[[responseObject objectForKey:@"head"] objectForKey:@"info"]];
            }
            else{
                [[BDHUD sharedManager] showWords:[THMangerTool language:@"HUD.nothing"]];
            }
        }
    } fail:^(id responseObject, NSError *error) {
        isMJRefresh=YES;
        [self.tableView.header endRefreshing];
        [[BDHUD sharedManager] dismissHUD];
        if ([[error.userInfo objectForKey:@"NSLocalizedDescription"] isEqualToString:@"请求超时。"]) {
            [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.time.out"]];
        }else {
            [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.network.interruption"]];
        }
        
    }];
}

#pragma -mark 安排发货
-(void)arrayDeliver
{
    [[BDHUD sharedManager] showBDHUD:self.view title:@"HUD.title"];
    sleep(0.5);
    [[BDHUD sharedManager] dismissHUD];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    params[@"orderCode"] = self.orderCode;
    params[@"parts"] = self.plateDicArr;
    
    [AFHttpTool postJsonDatawithUrl:@"/arrangeDelivery" parameters:[params mutableCopy] success:^(id responseObject) {
        if(1==[[[responseObject objectForKey:@"head"] objectForKey:@"status"] intValue]){
            if([[responseObject objectForKey:@"data"] isKindOfClass:[NSDictionary class]]){
             [[BDHUD sharedManager] showWords:[[responseObject objectForKey:@"head"] objectForKey:@"info"]];
                [self.navigationController popViewControllerAnimated:YES];
            }
            else
            {
                [self.tableView.header endRefreshing];
            }
        }
        else{
            //返回数据出问题 弹出服务器返回信息
            if([[[responseObject objectForKey:@"head"] allKeys] containsObject:@"info"]&&![UtilCheck DataIsNuLL:[[responseObject objectForKey:@"head"] objectForKey:@"info"]]){
                [[BDHUD sharedManager] showWords:[[responseObject objectForKey:@"head"] objectForKey:@"info"]];
            }
            else{
                [[BDHUD sharedManager] showWords:[THMangerTool language:@"HUD.nothing"]];
            }
            
        }
    } fail:^(id responseObject, NSError *error) {
        isMJRefresh=YES;
        [self.tableView.header endRefreshing];
        [[BDHUD sharedManager] dismissHUD];
        if ([[error.userInfo objectForKey:@"NSLocalizedDescription"] isEqualToString:@"请求超时。"]) {
            [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.time.out"]];
        }else {
            [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.network.interruption"]];
        }
        
    }];

}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.plateArray.count+1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row== 0) {
        settleDeliveryHeaderCell *cell = [tableView dequeueReusableCellWithIdentifier:@"settleDeliveryHeaderCell"];
        if (!cell) {
            cell = [[settleDeliveryHeaderCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"settleDeliveryHeaderCell"];
        }
        [cell setModel:self.model andBadPlateCount:self.badPlateNum andPlateCount:[self.model.tjCount integerValue]];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    else if(indexPath > 0)
    {
        settleDeliveryCell *cell = [tableView dequeueReusableCellWithIdentifier:@"settleDeliveryCell"];
        if (!cell) {
            cell = [[settleDeliveryCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"settleDeliveryCell"];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell setPlateModel:self.plateArray[indexPath.row-1]];
        cell.alterBtn.tag = indexPath.row -1;
        self.cellHeight = cell.cellHeight;
        
#pragma mark 修改按钮点击
        cell.clickBlock = ^(long tag)
        {
            CSSettleDeliveryUpPlateVC *view = [[CSSettleDeliveryUpPlateVC alloc]init];
            view.orderCode = self.orderCode;
            view.plate = self.plateDicArr[tag];
            view.plateTag = tag;
            view.delegate = self;
            view.allRecommendArr = [[NSMutableArray alloc]initWithArray:self.plateArray];
            [self.navigationController pushViewController:view animated:YES];
        };
        return cell;
    }
    return nil;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == 0)
        return 130.f;
    else
    {
        return self.cellHeight;
    }
}



-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.1;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}


#pragma -mark 获取替换的故障件
-(void)getNewPlate:(SettleDeliverPlate *)newPlate andTag:(NSInteger)tag
{

//    // 因为badSN还是用的原来没有修改.
//    SettleDeliverPlate *model = [[SettleDeliverPlate alloc] init];
//    model = self.plateArray[tag];
//    newPlate.badSN = model.badSN;
    NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] initWithDictionary:self.plateDicArr[tag]];
    [self.plateArray removeObjectAtIndex:tag];
    if ([Toolobject IsEmptyString:newPlate.partsCount ]) {
        newPlate.partsCount = [tempDict objectForKey:@"partsCount"];

    }
    [self.plateArray insertObject:newPlate atIndex:tag];
    
    NSMutableDictionary *newPlateDic = [[NSMutableDictionary alloc] init];
    
    newPlateDic[@"partsVersion"]=newPlate.partsVersion;
    newPlateDic[@"partsSN"]=newPlate.partsSN;
    newPlateDic[@"partsName"]=newPlate.partsName;
    newPlateDic[@"partsCode"]=newPlate.partsCode; 
    newPlateDic[@"attribution"]=newPlate.attribution;
    newPlateDic[@"location"]=newPlate.location;
    newPlateDic[@"id"] = newPlate.partID;
    newPlateDic[@"orderItemDetailId"] = newPlate.orderItemDetailId;
    
    // newPlateDic[@"badSN"] = model.badSN;
    

    newPlateDic[@"badSN"] = [tempDict objectForKey:@"badSN"];
    newPlateDic[@"partsCount"] = [tempDict objectForKey:@"partsCount"];

    [self.plateDicArr removeObjectAtIndex:tag];
    [self.plateDicArr insertObject:newPlateDic atIndex:tag];
    [self.tableView reloadData];
}







@end
